package com.ccloud.blog.modules.messageBoard.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccloud.common.core.model.LoginVal;
import com.ccloud.common.core.utils.OauthUtils;
import com.ccloud.blog.core.utils.AddressUtil;
import com.ccloud.blog.modules.messageBoard.domain.MessageBoard;
import com.ccloud.blog.modules.messageBoard.service.IMessageBoardService;
import com.ccloud.common.core.reqres.response.R;
import com.ccloud.common.core.utils.ValueUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chentailai
 * @since 2019-04-19
 */
@Slf4j
@RestController
@RequestMapping(value = "/messageBoard")
public class MessageBoardController {

    @Resource
    private AddressUtil addressUtil;

    @Resource
    private IMessageBoardService messageBoardService;


    @RequestMapping(value = "/getMessageBoardList")
    public R getMessageBoardList(@Param("current") Integer current, @Param("pageSize") Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(current);
        page.setSize(pageSize);
        List<Map<String, Object>> list = messageBoardService.getMsgBoardPagesList(page);
        page.setRecords(list);
        return R.ok(page, "获取列表成功");
    }

    @RequestMapping(value = "/getRecentlyMessages")
    public R getRecentlyMessages() {
        List<MessageBoard> list = messageBoardService.getRecentMessages();
        return R.ok(list, "获取最近留言列表成功" );
    }


    @RequestMapping(value = "/leaveMessage")
    public R leaveMessage(MessageBoard messageBoard, HttpServletRequest request) {
        String ipAddress = addressUtil.getIp(request);
        log.info("请求的地址是:{}", ipAddress);

        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal != null) {
            messageBoard.setCreateby(ValueUtils.parseInteger(loginVal.getUserId()));
        }
        messageBoard.setContent(StringEscapeUtils.escapeHtml(messageBoard.getContent()));
        //todo 重写坐标查询
        messageBoard.setCoordinate(addressUtil.getDistrict(ipAddress));
        messageBoardService.save(messageBoard);
        return R.ok(null, "留言成功");
    }

}

